from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import Brand
from apps.meiduo_admin.serializers.brand import BrandSerializer
from apps.meiduo_admin.utils.pagination import MeiduoPagination
from fdfs_client.client import Fdfs_client
from django.conf import settings


class BrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSerializer
    pagination_class = MeiduoPagination

    def create(self, request, *args, **kwargs):
        # 接收
        name = request.data.get('name')
        logo = request.data.get('logo')
        first_letter = request.data.get('first_letter')

        # 验证
        if not all([name, logo, first_letter]):
            return Response({'detail': '数据不完整'}, status=400)

        # 处理
        # １.上传图片
        logo_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        data = logo_client.upload_by_buffer(logo.read())
        logo_name = data.get('Remote file_id')

        # 2.创建品牌模型类对象
        instance = Brand.objects.create(name=name, logo=logo_name, first_letter=first_letter)

        # 响应
        serializer = self.get_serializer(instance)
        return Response(serializer.data, status=201)

    def update(self, request, *args, **kwargs):
        # 获取当前要修改的图片对象
        instance = self.get_object()

        # 接收
        name = request.data.get('name')
        logo = request.data.get('logo')
        first_letter = request.data.get('first_letter')

        # 验证
        if not all([name, first_letter]):
            return Response({'detail': '数据不完整'}, status=400)

        # 处理
        # 1.fdfs:删除旧照片，上传新照片
        if logo:
            # 如果用户上传新照片则修改
            logo_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
            # 删除===>instance.logo.name====>获取图片的额名称字符串
            logo_client.delete_file(instance.logo.name)
            # 上传
            data = logo_client.upload_by_buffer(logo.read())
            instance.logo = data.get('Remote file_id')

        # 2.修改对象
        instance.name = name
        instance.first_letter = first_letter

        instance.save()

        # 响应
        serializer = self.get_serializer(instance)
        return Response(serializer.data, status=201)

    def destroy(self, request, *args, **kwargs):
        # 查询当前的对象
        instance = self.get_object()

        # 删除logo
        logo_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        logo_client.delete_file(instance.logo.name)

        # 删除数据
        instance.delete()

        # 响应
        return Response(status=204)
